import { useReactive } from "ahooks";
import { useModel } from "umi";
import { useEffect } from "react";
import compress from "gql-compress";

const useAllMembers = () => {
    const { graphqlFetch } = useModel("global");
    const { applicationUuid } = useModel("application.info");

    const state = useReactive({
        loading: false,
        members: [],
    });

    // 加载组织所有已认证成员信息
    const loadAllMembers = async (isReload = false) => {
        if (!window.organizationUuid) return;
        if (!applicationUuid) return;
        let cacheKey = window.organizationUuid + "-" + window.applicationUuid + "-allMembers";
        if (isReload === false) {
            let cacheData = nodeCache.get(cacheKey);
            if (cacheData && cacheData.length > 0) return (state.members = cacheData);
        }
        state.loading = true;
        let res = await graphqlFetch({
            query,
            variables: {},
        });
        if (res) {
            state.members = res.a?.nodes || [];
            nodeCache.set(cacheKey, res.a?.nodes || [], 1 * 60); // 缓存两分钟
        }
        state.loading = false;
    };

    useEffect(() => {
        loadAllMembers();
    }, []);

    return { ...state, loadAllMembers };
};

const query = compress(`query MyQuery {
    a: allOrganizationMembers(condition: { omAust: "已认证" }) {
        nodes {
            omAust
            omAvta
            omBirt
            omCaus
            omDisu
            omEona
            omEouu
            omIdnu
            omIfim
            omJoti
            omName
            omNati
            omPhon
            omPosi
            omRnve
            omRoge
            omRoot
            omSign
            omUuid
        }
    }
}`);

export default useAllMembers;
